<?php
/**
 * Created by PhpStorm.
 * User: 独行侠
 * Date: 2018/2/7
 * Time: 20:17
 */

namespace App\Services\Distribution;


use App\Repositories\Distribution\DistributionModeRepository;
use App\Repositories\Distribution\DistributionTimeRepository;
use App\Services\Address\DeliverRegionOrderPeakService;
use Illuminate\Support\Facades\Cache;

class OrderDistributionTimeService
{
    /**
     * @var DistributionTimeRepository
     */
    protected $distributionTimeRepository;

    /**
     * @var DistributionModeRepository
     */
    protected $distributionModeRepository;

    /**
     * @var DeliverRegionOrderPeakService
     */
    protected $deliverRegionOrderPeakService;

    /**
     * @var array
     */
    protected $distributionTimeArray = [
        'today' => [],
        'tomorrow' => []
    ];

    /**
     * OrderDistributionTimeService constructor.
     * @param DeliverRegionOrderPeakService $deliverRegionOrderPeakService
     * @param DistributionTimeRepository $distributionTimeRepository
     * @param DistributionModeRepository $distributionModeRepository
     */
    public function __construct(DeliverRegionOrderPeakService $deliverRegionOrderPeakService, DistributionTimeRepository $distributionTimeRepository, DistributionModeRepository $distributionModeRepository)
    {
        $this->distributionTimeRepository = $distributionTimeRepository;
        $this->distributionModeRepository = $distributionModeRepository;
        $this->deliverRegionOrderPeakService = $deliverRegionOrderPeakService;
    }

    /**
     * 获取配送时间
     * @author Min
     * @param int $mode_id
     * @param int $wdr_id
     * @return array|mixed
     */
    public function getDistributieTime($mode_id = 0, $wdr_id = 0)
    {
        if(empty($mode_id)){
            return $this->distributionTimeArray;
        }

        //配送时间
        $distribution_time = $this->distributionTimeRepository->getDistributionTimeByModeId($mode_id);
        if(empty($distribution_time)){
            return $this->distributionTimeArray;
        }

        //配送方式
        $arrival_type = $this->distributionModeRepository->getDistributionModeArrivalType($mode_id);

        //区域订单峰值
        $order_peak = $this->deliverRegionOrderPeakService->getOrderPeakByWdrId($wdr_id);

        return $this->handelDistributieTime($distribution_time, $arrival_type, $wdr_id, $order_peak);
    }

    /**
     * 处理配送时间
     * @author Min
     * @param $distribution_time
     * @param $arrival_type
     * @param $wdr_id
     * @return array
     */
    public function handelDistributieTime($distribution_time, $arrival_type, $wdr_id, $order_peak)
    {

        //当前时间段的区域订单数量
        $order_total = Cache::get('order_best_time_num');

        //次日达区域 从明天开始
        $day = $arrival_type ? 1 : 0;

        $now_hour = date('H',time()).date('i',time());

        while (true){
            $title = '';
            $data = array();
            $time = strtotime("+{$day} day");
            $order_best_time_num = $order_total[date("Ymd", $time)];
            $date = date("Y-m-d", $time);
            $date_day = date("m月d日", $time);

            foreach ($distribution_time as $key=>$value){
                $closing_time = str_replace(":","",$value['closing_time']);
                $start_time = str_replace(":","",$value['start_time']);

                $best_time = $this->get_best_time($date, $value['start_time'], $value['end_time']);
                $order_num = $order_best_time_num[$wdr_id.'-'.$best_time]; //当前时间段订单数量

                $peak_num = $this->getDistributionTimeOrderPeak($value['id'], $order_peak); //订单峰值配置
                $is_free_single = $this->getDistributionTimeIsFreeSingle($value['id'], $order_peak); //是否超时免单

                if($order_num >= $peak_num && $peak_num > 0){
                    continue;
                }

                //当天
                if($day == 0){
                    if ($closing_time > $now_hour && $start_time > $closing_time) {
                        $data[] = $this->get_time($order_num, $peak_num, $is_free_single, $best_time, $date_day, $value, $day, 0);
                    }
                    $title = '当天送达';
                }else{
                    if($start_time>$closing_time){
                        $data[] = $this->get_time($order_num, $peak_num, $is_free_single, $best_time, $date_day, $value, $day);
                    }
                    $title = $date_day;
                }

                if ($start_time < $closing_time && $day != 0) {
                    //开始时间大于截单时间，将时间定位次日
                    $data[] = $this->get_time($order_num, $peak_num, $is_free_single, $best_time, $date_day, $value, $day, 0);
                }

            }

            if(!$this->distributionTimeArray['today'] && $data){
                $this->distributionTimeArray['today'] = $data;
                $this->distributionTimeArray['today_title'] = $title;
            }else{
                $this->distributionTimeArray['tomorrow'] = $data;
            }

            $this->distributionTimeArray['tomorrow_title'] = $title;

            if($this->distributionTimeArray['today'] && $this->distributionTimeArray['tomorrow']){
                break;
            }

            $day++;
        }

        return $this->distributionTimeArray;
    }

    /**
     * @author Min
     * @param $order_peak
     * @param $time_id
     * @return int
     */
    protected function getDistributionTimeOrderPeak($order_peak, $time_id)
    {
        if(!empty($order_peak[$time_id])) {
            return $order_peak[$time_id]['order_peak'];
        } else {
            return 0;
        }
    }

    /**
     * @author Min
     * @param $order_peak
     * @param $time_id
     * @return int
     */
    protected function getDistributionTimeIsFreeSingle($order_peak, $time_id)
    {
        if(!empty($order_peak[$time_id])) {
            return $order_peak[$time_id]['is_free_single'];
        } else {
            return 0;
        }
    }

    /**
     * @param $date
     * @param $start_time
     * @param $end_time
     * @return string
     */
    protected function get_best_time($date, $start_time, $end_time){
        $best_time_start = strtotime($date." ". $start_time);
        $best_time = strtotime($date." ". $end_time);
        return $best_time_start.'-'.$best_time;
    }

    /**
     * 获取时间转换格式
     * Created By caicm
     * @param $order_num
     * @param $peak_num
     * @param $is_free_single
     * @param $best_time
     * @param $date_day
     * @param $value
     * @param $day
     * @param int $tomorrow
     * @return array
     */
    protected function get_time($order_num, $peak_num, $is_free_single, $best_time, $date_day, $value, $day, $tomorrow=1){
        $title = '明日';
        if($day==0 && $tomorrow==0){
            $title = $date_day = '今日';
        }
        return array(
            "order_num" => $order_num ? $order_num : 0,
            "order_peak" => $peak_num,
            "value" => $best_time,
            "title" => "{$date_day} {$value['start_time']} - {$value['end_time']}",
            'closing'	=>	$title.$value['closing_time'],
            'is_free_single' => $is_free_single ? $is_free_single : 0
        );
    }


}